package com.geeksaga.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.geeksaga.common.constant.SagaConstants;
import com.geeksaga.common.util.StringUtils;
import com.geeksaga.domain.Project;
import com.geeksaga.domain.Spec;
import com.geeksaga.domain.User;

/**
 * @author newbie
 * @since 0.1
 */
public class SpecValidator implements Validator {
    private Project project = null;
    private String command = null;
    
    public SpecValidator() {
    }
    
    public SpecValidator(Project project, String command) {
    	this.project = project;
    	this.command = command;
    }
    
    /* (non-Javadoc)
     * @see org.springframework.validation.Validator#supports(java.lang.Class)
     */
    @SuppressWarnings("rawtypes")
	public boolean supports(Class clazz) {
        return clazz.equals(User.class);
    }
    
    /* (non-Javadoc)
     * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
     */
    public void validate(Object object, Errors errors) {
        Spec spec = (Spec) object;
        
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPasswd", "error.empty.userPasswd", "error...");

		if (!SagaConstants.REMOVE.equals(command)) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "specTitle", "error.empty.title", "error...");
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userNick", "error.empty.userNick", "error...");

			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "specDescription", "error.empty.content", "error...");

			if (project != null) {
				if (!StringUtils.isEmpty(spec.getUserEmail()) && spec.getUserEmail().indexOf(SagaConstants.AT) < 0)
					errors.rejectValue("userEmail", "error", "error...");
			}
		}
    }
}